package com.laihuichuxing.demo;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author YangGuang
 * @program: learn-thread
 * @description:
 * @create: 2018-12-14 10:09
 **/
public class Snatch {

    // 使用阻塞队列,队列大小根据情况自己定义
    static final LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<>(5);

    // 创建线程数量啊为cpu核心数的两倍的线程池
    static ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2);

    // 是否有商品
    static volatile boolean flag = true;

    // 初始是0
    static AtomicInteger integer = new AtomicInteger(0);

    public static void main(String[] args) {
        // 模拟100个请求
        for (int i = 0; i < 100; i ++) {
            executorService.execute(new Producer(String.valueOf(i)));
            executorService.execute(new Consumer());
        }
        executorService.shutdown();
    }

    static class Producer implements Runnable {

        private String name;

        public Producer(String name) {
            this.name = name;
        }

        @Override
        public void run() {
            try {
                queue.put(name);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    static class Consumer implements Runnable {

        @Override
        public void run() {
            try {
                String name = queue.take();
                handle(name);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private static void handle(String name) {
        System.out.println("Thread:[" + Thread.currentThread().getName() +"]");
        if (flag) {
            int increment = integer.getAndIncrement();
            if (increment >= 4) {
                flag = false;
            }
            System.out.printf("====================用户:[%s]抢到了商品\n",name + "=======================");
        } else {
            System.out.printf("用户:[%s]没有抢到商品\n",name);
        }
    }
}
